package com.puyuba.puyuba.view.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.hjq.permissions.OnPermissionCallback;
import com.hjq.permissions.Permission;
import com.hjq.permissions.XXPermissions;
import com.hjq.toast.ToastUtils;
import com.hyphenate.chat.EMClient;
import com.hyphenate.chat.EMConversation;
import com.hyphenate.chat.EMCustomMessageBody;
import com.hyphenate.chat.EMMessage;
import com.hyphenate.easeui.constants.EaseConstant;
import com.puyuba.puyuba.R;
import com.puyuba.puyuba.SkinApplication;
import com.pyb.java.basemodule.BaseActivity;
import com.puyuba.puyuba.bean.SwapMobileBean;
import com.puyuba.puyuba.network.Constants;
import com.pyb.java.cache.CacheUserInfo;
import com.pyb.java.cache.SPHelper;
import com.pyb.java.commonutil.utils.StringUtil;
import com.pyb.java.network.RequestBodyUtil;
import com.pyb.java.network.ResponseEntity;
import com.pyb.java.network.RetrofitManger;
import com.pyb.java.network.observers.ResponseObserve;

import com.pyb.java.network.scheduler.RxSchedulers;
import com.puyuba.puyuba.network.UserApi;
import com.pyb.java.commonutil.ToastHelper;

import com.puyuba.puyuba.utils.custommessage.ChatFragment;
import com.pyb.java.commonutil.eventbus.EventBusKeys;
import com.pyb.java.commonutil.eventbus.EventBusMessage;
import com.pyb.java.commonutil.eventbus.EventBusUtils;
import com.puyuba.puyuba.view.dialog.EducationDemandDialog;
import com.puyuba.puyuba.view.dialog.ProfessionDemandDialog;
import com.puyuba.puyuba.view.dialog.SelectDemandDialog;

import org.greenrobot.eventbus.Subscribe;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import io.reactivex.disposables.Disposable;
import okhttp3.RequestBody;

public class ChatActivity extends BaseActivity {

    private LinearLayout llChangePhone;
    private ImageView ivChangePhone;
    private TextView tvChangePhone;
    private LinearLayout llSendDemand;
    private ImageView ivSendDemand;
    private TextView tvSendDemand;
    private ChatFragment chatFragment;
    private String title;
    private EMMessage message;
    private String conversationId;
    private EMMessage customMessage;
    private ImageView ivBack;
    private TextView tvTitle;
    private TextView tvRole;
    private int userrole; // 1 学生  2 老师
    private int uiOptions;
    private ProfessionDemandDialog professionDemandDialog;
    private EducationDemandDialog demandDialog;

    @Override
    public int getLayoutId() {
        return R.layout.activity_chat;
    }

    public static void startActivity(Context context,String id) {
        if (StringUtil.isEmpty(id)){
            ToastUtils.show("对方未注册环信");
        }else {
            Intent intent = new Intent(context, ChatActivity.class);
            intent.putExtra(EaseConstant.EXTRA_CONVERSATION_ID, id);
            intent.putExtra(EaseConstant.EXTRA_CHAT_TYPE, EMMessage.ChatType.Chat);
            context.startActivity(intent);
        }
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        llChangePhone = (LinearLayout) findViewById(R.id.ll_change_phone);
        ivChangePhone = (ImageView) findViewById(R.id.iv_change_phone);
        tvChangePhone = (TextView) findViewById(R.id.tv_change_phone);
        llSendDemand = (LinearLayout) findViewById(R.id.ll_send_demand);
        ivSendDemand = (ImageView) findViewById(R.id.iv_send_demand);
        tvSendDemand = (TextView) findViewById(R.id.tv_send_demand);
        ivBack = (ImageView) findViewById(R.id.iv_back);
        tvTitle = (TextView) findViewById(R.id.tv_title);
        tvRole = (TextView) findViewById(R.id.tv_role);

        initData();
        initListener();
//        EMMessageListener msgListener = new EMMessageListener() {
//            @Override
//            public void onMessageReceived(List<EMMessage> messages) {
//                chatFragment.chatLayout.getChatMessageListLayout().refreshToLatest();
//            }
//
//            @Override
//            public void onCmdMessageReceived(List<EMMessage> messages) {
////                chatFragment.chatLayout.getChatMessageListLayout().refreshToLatest();
//            }
//
//            @Override
//            public void onMessageRead(List<EMMessage> messages) {
//
//            }
//
//            @Override
//            public void onMessageDelivered(List<EMMessage> messages) {
//                chatFragment.chatLayout.deleteMessage(customMessage);
//            }
//
//            @Override
//            public void onMessageRecalled(List<EMMessage> messages) {
//
//            }
//
//            @Override
//            public void onMessageChanged(EMMessage message, Object change) {
//
//            }
//        };
//        EMClient.getInstance().chatManager().addMessageListener(msgListener);
    }

    private void initData() {
        EventBusUtils.register(ChatActivity.this);
        int id = CacheUserInfo.getInstance().getIdentity();
        if (id == 30 ||id == 25){
            //学生身份
            userrole = 1;
        }else {
            userrole = 2;
            tvSendDemand.setText("发测评");
            tvRole.setText("学生");
        }

        conversationId = getIntent().getStringExtra(EaseConstant.EXTRA_CONVERSATION_ID);
        SPHelper.putString("conversationId",conversationId);
        tvTitle.setText(conversationId);

        //use EaseChatFratFragment
        chatFragment = new ChatFragment();
        //pass parameters to chat fragment
        chatFragment.setArguments(getIntent().getExtras());
        getSupportFragmentManager().beginTransaction().add(R.id.ec_container, chatFragment).commit();
        classrequestPermission();
    }

    private void initListener() {
        llChangePhone.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                swapmobile(0,conversationId, CacheUserInfo.getInstance().getId());
            }
        });
        llSendDemand.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                initDialog();
            }
        });
        ivBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
    }
    //查询手机号交换信息
    public void swapmobile(int type,String other_uid,int uid) {
        //type  1交换 0查询 默认0
        HashMap<String, Object> map = new HashMap<>();
        map.put("other_uid", other_uid);
        map.put("type", type);
        map.put("uid", uid);
        RequestBody bodyByMap = RequestBodyUtil.getRequestBodyByMap(map);
        RetrofitManger.getInstance().createService(UserApi.class)
                .swapmobile(bodyByMap)
                .compose(RxSchedulers.<ResponseEntity<SwapMobileBean>>applySchedulers())
                .subscribe(new ResponseObserve<SwapMobileBean>(){

                    @Override
                    public void onSuccess(ResponseEntity<SwapMobileBean> responseEntity) {
                        if (responseEntity.getData().getIs_swap()==1){
                            //已交换  直接本地插入消息    refreshMessages 刷新消息  refreshToLatest 刷新移到最后一条
                            insertPhoneMsg(responseEntity.getData().getMobile(),conversationId);
                            chatFragment.chatLayout.getChatMessageListLayout().refreshToLatest();
                        }else {
                            //未交换 发送消息
                            chatFragment.sendPhoneMsg(CacheUserInfo.getInstance().getsUserInfo().getUser().getRname(),System.currentTimeMillis()+"","phone");
                            chatFragment.chatLayout.sendMessageFinish(message);
                        }
                    }

                    @Override
                    public void onFail(String errorMsg) {
                        if (errorMsg != null&&!errorMsg.equals("")){
                            ToastHelper.show(errorMsg);
                        }else {
                            ToastHelper.show("服务器繁忙，请稍后再试");
                        }
                    }

                    @Override
                    public void onSubscribeStart(@NonNull Disposable disposable) { }

                });
    }

    //本地插入显示手机号弹窗
    public void insertPhoneMsg(String phone,String name) {
        EMMessage phonemsg = EMMessage.createSendMessage(EMMessage.Type.CUSTOM);
        EMCustomMessageBody phonebody = new EMCustomMessageBody(Constants.CHANGE_PHONE_CUSTOM_MSG);
        Map<String,String> params = new HashMap<>();
        params.put(Constants.PHONE,phone);
        params.put(Constants.USER_NAME,name);
        phonebody.setParams(params);
        phonemsg.addBody(phonebody);
        insertMsg(phonemsg);
    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBusUtils.unRegister(ChatActivity.this);
    }

    //删除当前会话的某条聊天记录
    private void deleteMsg(EMMessage message){
        EMConversation conversation = EMClient.getInstance().chatManager().getConversation(conversationId);
        conversation.removeMessage(message.getMsgId());
    }

    //根据会话插入消息
    private void insertMsg(EMMessage msg){
        EMConversation conversation = EMClient.getInstance().chatManager().getConversation(conversationId);
        conversation.insertMessage(msg);
    }

    private void initDialog() {
        //去除dialog状态栏
        uiOptions = View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
                | View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
                | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                | View.SYSTEM_UI_FLAG_IMMERSIVE
                | View.SYSTEM_UI_FLAG_FULLSCREEN;
        final SelectDemandDialog selectDemandDialog = new SelectDemandDialog(ChatActivity.this);
        selectDemandDialog.setOnClickBottomListener(new SelectDemandDialog.OnClickBottomListener() {

            @Override
            public void initprofessionDialog() {
                if (userrole == 1){
                    //学生
                    initzhiye();
                }else {
                    //老师
                    chatFragment.sendPhoneMsg(CacheUserInfo.getInstance().getsUserInfo().getUser().getRname(),System.currentTimeMillis()+"","zhiye");
                    chatFragment.chatLayout.sendMessageFinish(message);
                }
            }

            @Override
            public void initdemandDialog() {
                if (userrole == 1){
                    //学生
                    initxueli();
                }else {
                    chatFragment.sendPhoneMsg(CacheUserInfo.getInstance().getsUserInfo().getUser().getRname(),System.currentTimeMillis()+"","xueli");
                    chatFragment.chatLayout.sendMessageFinish(message);
                }
            }
        }).show();
        selectDemandDialog.getWindow().getDecorView().setSystemUiVisibility(uiOptions);
    }

    private void initxueli() {
        demandDialog = new EducationDemandDialog(ChatActivity.this);
        demandDialog.setOnClickBottomListener(new EducationDemandDialog.OnClickBottomListener() {
            @Override
            public void commit(String currentEdu, String targetEdu, String time, int easy) {
                commitData(CacheUserInfo.getInstance().getHxUid(),2,"","","","",currentEdu,targetEdu,time,easy);
            }
        }).show();
        demandDialog.getWindow().getDecorView().setSystemUiVisibility(uiOptions);
    }

    private void initzhiye() {
        professionDemandDialog = new ProfessionDemandDialog(ChatActivity.this);
        professionDemandDialog.setOnClickBottomListener(new ProfessionDemandDialog.OnClickBottomListener() {
            @Override
            public void commit(String age, String job, String company, String profession, String year) {
                commitData(CacheUserInfo.getInstance().getHxUid(),1,age,job,company,profession,"","",year,0);
            }
        }).show();
        professionDemandDialog.getWindow().getDecorView().setSystemUiVisibility(uiOptions);
    }

    @Subscribe
    public void onMoonEvent(EventBusMessage messageEvent) {
        if (messageEvent.getKey() == EventBusKeys.REFRESH_MSG_LIST) {
            chatFragment.chatLayout.getChatMessageListLayout().refreshToLatest();//刷新并移动到最底部
        }else if (messageEvent.getKey() == EventBusKeys.SHOW_ZHIYE) {
            initzhiye();
        }else if (messageEvent.getKey() == EventBusKeys.SHOW_XUELI) {
            initxueli();
        }
    }
    //提交需求
    private void commitData(String uid,int type,String age,String job,String company,String industry,String now_edu,String aim_edu,String year,int diff_level) {

        showLoadingDialog();
        HashMap<String, Object> map = new HashMap<>();
        map.put("uid", uid);
        map.put("type", type);
        map.put("age", age);
        map.put("job", job);
        map.put("company", company);
        map.put("industry", industry);
        map.put("now_edu", now_edu);
        map.put("aim_edu", aim_edu);
        map.put("year", year);
        map.put("diff_level", diff_level);
        RequestBody bodyByMap = RequestBodyUtil.getRequestBodyByMap(map);
        RetrofitManger.getInstance().createService(UserApi.class)
                .submitneed(bodyByMap)
                .compose(RxSchedulers.<ResponseEntity<Object>>applySchedulers())
                .subscribe(new ResponseObserve<Object>(){

                    @Override
                    public void onSuccess(ResponseEntity<Object> responseEntity) {
                        closeLoadingDialog();
                        ToastHelper.show("提交成功");
                        chatFragment.submitneed(type,age,job,company,industry,now_edu,aim_edu,year,diff_level);
                        chatFragment.chatLayout.sendMessageFinish(message);
                    }

                    @Override
                    public void onFail(String errorMsg) {
                        closeLoadingDialog();
                        if (errorMsg != null&&!errorMsg.equals("")){
                            ToastHelper.show(errorMsg);
                        }else {
                            ToastHelper.show("服务器繁忙，请稍后再试");
                        }
                    }

                    @Override
                    public void onSubscribeStart(@io.reactivex.annotations.NonNull Disposable d) {
                        addDisposable(d);
                    }
                });

    }
    /**
     * 权限申请
     */
    private void classrequestPermission() {
        XXPermissions.with(this)
                .permission(Permission.RECORD_AUDIO)
                .permission(Permission.CAMERA)
                .request(new OnPermissionCallback() {
                    @Override
                    public void onGranted(List<String> permissions, boolean all) {
                        if (all) {
                            //toast("获取权限成功");
//                            takePhoto();
                        } else {
                            //"获取部分权限成功，但部分权限未正常授予");
                        }
                    }

                    @Override
                    public void onDenied(List<String> permissions, boolean never) {
                        if (never) {
                            //toast("被永久拒绝授权，请手动授予录音和日历权限");
                            // 如果是被永久拒绝就跳转到应用权限系统设置页面
                            XXPermissions.startPermissionActivity(SkinApplication.getInstance(), permissions);
                        } else {
                            //toast("获取权限失败");
                        }
                    }
                });
    }

}
